package cn.jaye.fabric.domain.model;

import cn.jaye.fabric.FabricServiceApplication;
import cn.jaye.fabric.common.constants.exception.ExceptionEnum;
import cn.jaye.fabric.common.model.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.SpringApplication;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jaye
 * @create 2018-05-15 15:26
 */
@Getter
@Setter
public class ChainCode {
    private String name;
    private String version;
    private String path;
    private String location;
    private String fcn;
    private String[] args;

    public ChainCode(String name, String version, String path) {
        this.name = name;
        this.version = version;
        this.path = path;
    }

    public ChainCode(String name, String version, String path, String location, String fcn, Object args) {
        this.name = name;
        this.version = version;
        this.path = path;
        this.location = location;
        this.fcn = fcn;
        this.args = convert(args);
    }

    private String[] convert(Object args) {
        String[] result = new String[1];
        try {
            String data = JSONObject.toJSONString(args, SerializerFeature.WriteMapNullValue);
            if (data.startsWith("[") && data.endsWith("]")) {
                return ((List<String>) args).toArray(new String[0]);
            } else {
                result[0] = data;
            }
        } catch (Exception e) {
            throw new ServiceException(ExceptionEnum.INVALID_PARAMETER);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
